/*
 * @Author: bear
 * @Date: 2022-08-01 09:56:18
 * @LastEditors: bear
 * @LastEditTime: 2022-08-04 15:36:57
 * @Description: your project
 * @version: 1.0
 */
"use strict";

import {
  app,
  BrowserWindow,
  ipcMain,
  globalShortcut,
  // Menu,
  autoUpdater,
  dialog,
} from "electron";
let win;
async function createWindow() {
  // Create the browser window.
  // Menu.setApplicationMenu(null);//隐藏顶部菜单如果设置为null，自定义的也不会显示
  win = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      nodeIntegration: true, //开启true这一步很重要,目的是为了vue文件中可以引入node和electron相关的API
      contextIsolation: false,
      enableRemoteModule: true,
    },
  });
  ipcMain.on("update", (e, data) => {
    console.log(data);
    e.sender.send("something1", "我是主进程返回的值");
  });
  // 渲染进程之间的通信
  global.sharedObject = {
    someProperty: "默认的=====default value",
  };

  if (process.env.WEBPACK_DEV_SERVER_URL) {
    // Load the url of the dev server if in development mode
    await win.loadURL(process.env.WEBPACK_DEV_SERVER_URL);
    // if (!process.env.IS_TEST) win.webContents.openDevTools();
  } else {
    // Load the index.html when not in development
    win.loadURL("app://./index.html");
  }
}

// Quit when all windows are closed.
app.on("window-all-closed", () => {
  // On macOS it is common for applications and their menu bar
  // to stay active until the user quits explicitly with Cmd + Q
  if (process.platform !== "darwin") {
    app.quit();
  }
});

app.on("activate", () => {
  if (BrowserWindow.getAllWindows().length === 0) createWindow();
});

app.on("ready", async () => {
  // 顶部菜单
  require("./unit/menu.js");
  createWindow();
  globalShortcut.register("Control+Alt+y", () => {
    // Do stuff when Y and either Command/Control is pressed.
    win.webContents.openDevTools({ mode: "bottom" }); // 打开开发者工具/调试工具
  });
  //每次启动程序，就检查更新
  checkUpdate();
});

function checkUpdate() {
  //检测更新
  autoUpdater.checkForUpdates();

  //监听'error'事件
  autoUpdater.on("error", (err) => {
    console.log(err);
  });

  //监听'update-available'事件，发现有新版本时触发
  autoUpdater.on("update-available", () => {
    console.log("found new version");
  });

  //默认会自动下载新版本，如果不想自动下载，设置autoUpdater.autoDownload = false

  //监听'update-downloaded'事件，新版本下载完成时触发
  autoUpdater.on("update-downloaded", () => {
    dialog
      .showMessageBox({
        type: "info",
        title: "应用更新",
        message: "发现新版本，是否更新？",
        buttons: ["是", "否"],
      })
      .then((buttonIndex) => {
        if (buttonIndex.response == 0) {
          //选择是，则退出程序，安装新版本
          autoUpdater.quitAndInstall();
          app.quit();
        }
      });
  });
}
